import React from 'react';
import { Navigate } from 'react-router-dom';
import { Spin } from 'antd';
import { useAuth } from '../contexts/AuthContext';

interface ProtectedRouteProps {
  children: React.ReactElement;
  requireAdmin?: boolean;
}

const ProtectedRoute: React.FC<ProtectedRouteProps> = ({ children, requireAdmin = false }) => {
  const { user, loading } = useAuth();

  if (loading) {
    return (
      <div style={{ display: 'flex', justifyContent: 'center', alignItems: 'center', height: '100vh' }}>
        <Spin size="large" />
      </div>
    );
  }

  if (!user) {
    return <Navigate to="/login" replace />;
  }

  // Block users with only AppUser role from accessing admin system
  const hasAdminRole = user.roles?.some(role =>
    role === 'PlatformUser' || role === 'Administrator' || role === 'SystemAdministrator'
  );

  if (!hasAdminRole) {
    return <Navigate to="/login" replace />;
  }

  // Check if route requires Administrator role
  if (requireAdmin && !user.roles?.includes('Administrator')) {
    return <Navigate to="/" replace />;
  }

  return children;
};

export default ProtectedRoute;
